package com.sy.rabbitmq.quickstart;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.sy.rabbitmq.TestProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * rabbitmq消费端-第一个demo
 */
public class Comsumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.创建一个链接工厂,配置初始化参数
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(TestProperties.getIp());
        connectionFactory.setPort(TestProperties.getPort());
        connectionFactory.setVirtualHost("/");
        //2.创建链接
        Connection connection = connectionFactory.newConnection();

        //3.通过链接创建一个Channel,再通过Channel发送消息
        Channel channel = connection.createChannel();

        //4.声明(创建)一个队列 - 队列名,是否持久化,是否独占队列(仅此链接),是否服务器将在不再使用它时将其删除,附加参数map格式
        java.lang.String queueName = "test001";
        channel.queueDeclare(queueName,true,false,false,null);

        //5.创建消费者  - channel
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        //6.设置Channel - 指定队列,是否在自动签收(false的话,接受队列任务后需要手工回复签收),消费者对象
        channel.basicConsume(queueName,true,queueingConsumer);

        //7.获取队列任务
        while(true){
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println(msg);
        }
//        channel.close();
//        connection.close();
    }
}
